package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

  /*  @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            Toast.makeText(this, "点击了后退",Toast.LENGTH_SHORT).show();
            return true;
    }else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP){
            Toast.makeText(this, "音量增加",Toast.LENGTH_SHORT).show();
            return true;
        }else if (keyCode ==KeyEvent.KEYCODE_BACK){


        }



     return super.onKeyDown(keyCode, event);
    }
}*/

    long exitTime=0;
    @SuppressLint("WrongConstant")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {

                String applicationName = getResources().getString(
                        R.string.app_name);
                String msg = "再按一次返回键退出" + applicationName;

                Toast.makeText(MainActivity.this, msg, 0).show();

                exitTime = System.currentTimeMillis();
            } else {

                finish();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }}